<?php

/*
 * @Date: 2025-08-19 23:01:29
 * @LastEditors: 贾二小 erxiao.jia@outlook.com
 * @LastEditTime: 2025-10-28 21:15:33
 * @FilePath: /admin-api/app/Http/Controllers/UserController.php
 */

namespace App\Http\Controllers;

use App\Http\Requests\StoreUserRequest;
use App\Http\Requests\UpdateUserRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use DragonCode\Support\Facades\Filesystem\File;
use Illuminate\Support\Facades\Storage;
use Laravolt\Avatar\Avatar;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $users = User::key(request('key'))->gender(request('gender'))->latest()->paginate(request('per_page', 15));

        return UserResource::collection($users);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreUserRequest $request, User $user)
    {
        $user->fill($request->input() + ['password' => bcrypt('123456')])->save();

        // 生成并保存头像
        $local_path = Storage::disk('local')->path("avatars/{$user->id}.jpg");

        (new Avatar())->create($user->email)
            ->setDimension(256, 256)
            ->setFontSize(120)
            ->save($local_path, 90);

        //上传到阿里云
        $path = Storage::putFile('avatars', $local_path);

        // 删除文件
        Storage::disk('local')->delete("avatars/{$user->id}.jpg");

        // 保存路径到数据库
        $user->update(['avatar' => $path]);
        // 生成临时url
        //dd(  Storage::temporaryUrl('avatars/RGijwo9bPxCBiIXm28BFfORGiCmweCV39DHqx4MH.jpg',now()->addMinutes(5)));

        return $this->success('新增成功', $user);
    }

    /**
     * Display the specified resource.
     */
    public function show(User $user)
    {
        return $this->success(data: new UserResource($user));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateUserRequest $request, User $user)
    {
        $user->fill($request->input())->save();

        return $this->success('更新成功');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(User $user)
    {
        $user->delete();

        return $this->success(message: '删除成功');
    }

    public function roles(User $user)
    {
        return $this->success(data: $user->roles->pluck('id'));
    }

    public function syncRoles(User $user)
    {
        $user->roles()->sync(request()->input('roles', []));
        return $this->success('更新成功');
    }
}
